﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml.Drawing.Charts;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities;
using Sirenix.Utilities.Editor;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;

namespace BearUtil
{
    /// <summary>
    /// 文件预览窗口
    /// </summary>
    public class ExcelViewWindow : OdinEditorWindow
    {
        public static List<ExcelViewWindow> windows;
        
        public string ExcelPath
        {
            get;
            set;
        }

        /// <summary>
        /// 持有数据
        /// </summary>
        [HideLabel, HideInInspector]
        public List<ExcelData> datas;
        [HideLabel, SerializeField]
        private ExcelData curSheet;
        [HideLabel, TableMatrix(HorizontalTitle = "剧情对话表", ResizableColumns = false, RowHeight = 16)]
        public string[,] curdata;

        // 是否是 excel 文件
        private bool isFile;

        private int addCol = 1;
        private int addRow = 1;

        private int rmCol = 1;
        private int rmRow = 1;
        
        #region Open
        public static void OpenWindow(string filePath)
        {
            if (ExcelViewWindow.windows == null)
                ExcelViewWindow.windows = new List<ExcelViewWindow>();
            
            if (ExcelViewWindow.windows == null) ExcelViewWindow.windows = new List<ExcelViewWindow>();
            var fileName = Path.GetFileNameWithoutExtension(filePath);

            if (ExcelViewWindow.windows.Count() > 0)
            {
                var wd = ExcelViewWindow.windows.Find(w =>
                {
                    return w.titleContent.text == fileName;
                });
            
                wd.Show();
                wd.Focus();
                return;
            }
            
            var window = GetWindow<ExcelViewWindow>();
            window.titleContent = new GUIContent(fileName);
            window.position = GUIHelper.GetEditorWindowRect().AlignCenter(700, 700);
            window.ExcelPath = filePath;
            window.OnInit(true);
            
            ExcelViewWindow.windows.Add(window);
        }
        
        public static void OpenWindow(ExcelData data)
        {
            if (ExcelViewWindow.windows == null)
                ExcelViewWindow.windows = new List<ExcelViewWindow>();
            
            if (ExcelViewWindow.windows.Count() > 0)
            {
                var wd = ExcelViewWindow.windows.Find(w =>
                {
                    return w.titleContent.text == data.sheetName;
                });
            
                wd.Show();
                wd.Focus();
                return;
            }
            
            var window = GetWindow<ExcelViewWindow>();
            window.titleContent = new GUIContent(data.sheetName);
            window.position = GUIHelper.GetEditorWindowRect().AlignCenter(700, 700);

            window.curSheet = data;
            window.curdata = data.Datas;
            
            ExcelViewWindow.windows.Add(window);
        }
        
        #endregion


        private const string excelexePath = "C:\\Program Files\\Microsoft Office\\Office16\\EXCEL.EXE";
        protected override void OnGUI()
        {
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("刷新"))
            {
                OnInit();
            }
            
            if (GUILayout.Button("覆盖保存"))
            {
                curSheet.SaveData(curdata);
                curSheet.LoadTransformData();
                ExcelEdit.WriteExcel(curSheet, ExcelDataGenerator.Instance.OutputExcelFold);
            }

            if (isFile)
            {
                if (GUILayout.Button("打开源文件"))
                {
                    // 可能会打不开
                    Process.Start(excelexePath, ExcelPath);
                }
            }

            GUILayout.EndHorizontal();

            if (datas != null && datas.Count() > 0)
            {
                GUILayout.BeginHorizontal();
                for (int i = 0; i < datas.Count(); i++)
                {
                    if (GUILayout.Button(datas[i].sheetName))
                    {
                        curSheet = datas[i];
                        curdata = curSheet.Datas;
                    }
                }
                GUILayout.EndHorizontal();
            }

            base.OnGUI();
            
            GUILayout.BeginHorizontal();

            addCol = Convert.ToInt32(GUILayout.TextField(addCol.ToString(), 8));
            if (GUILayout.Button("增加列"))
            {
                curSheet.col += addCol;
                updateData();
                curSheet.SaveData(curdata);
            }
            
            addRow = Convert.ToInt32(GUILayout.TextField(addRow.ToString(), 8));
            if (GUILayout.Button("增加行"))
            {
                curSheet.row += addRow;
                updateData();
                curSheet.SaveData(curdata);
            }

            GUILayout.EndHorizontal();
            
            GUILayout.BeginHorizontal();

            rmCol = Convert.ToInt32(GUILayout.TextField(rmCol.ToString(), 8));
            if (GUILayout.Button("减少列") && curSheet.col > rmCol)
            {
                curSheet.col -= rmCol;
                updateData();
                curSheet.SaveData(curdata);
            }
            
            rmRow = Convert.ToInt32(GUILayout.TextField(rmRow.ToString(), 8));
            if (GUILayout.Button("减少行") && curSheet.row > rmRow)
            {
                curSheet.row -= rmRow;
                updateData();
                curSheet.SaveData(curdata);
            }

            GUILayout.EndHorizontal();
        }

        private void updateData()
        {
            string[,] tmpData = new string[curSheet.col, curSheet.row];
            int col = Mathf.Min(tmpData.GetLength(0), curdata.GetLength(0));
            int row = Mathf.Min(tmpData.GetLength(1), curdata.GetLength(1));
            for (int i = 0; i < col; i++)
            {
                for (int j = 0; j < row; j++)
                {
                    tmpData[i, j] = curdata[i, j];
                }
            }

            curdata = tmpData;
        }

        protected void OnInit(bool isFile = false)
        {
            if (ExcelPath == null)
                return;

            ExcelEdit.LoadExcel(ExcelPath, ref datas);

            if (datas != null && datas.Count() > 0)
            {
                this.isFile = isFile;
                curSheet = datas[0];
                curdata = curSheet.Datas;    
            }
        }

        protected  void OnDestroy()
        {
            if (ExcelViewWindow.windows == null)
            {
                Debug.Log("ExcelViewWindow 数据错误");
                return;
            }
            if (curSheet != null)
                curSheet.SaveData(curdata);
            ExcelViewWindow.windows.Remove(this);
        }
    }   
}
